package com.cyanite.playlv2;


import com.cyanite.playlv2.app.LoadableListActivity;
import com.cyanite.playlv2.app.LoadableListActivityWithView;
import com.cyanite.playlv2.widget.SearchResultListAdapter;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.SearchResult;
import com.cyanite.playlv2api.types.Task;
import com.cyanite.playlv2api.types.TaskMini;
import com.cyanite.playlv2api.types.Trip;
import com.cyanite.playlv2api.types.TripMini;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

public class SearchResultActivity extends LoadableListActivity{
    public static final String EXTRA_SEARCH_TRIP = PlayLv2.PACKAGE_NAME
    + ".SearchResultActivity.EXTRA_SEARCH_TRIP";
    
    public static final String EXTRA_SEARCH_QUERY = PlayLv2.PACKAGE_NAME
    + ".SearchResultActivity.EXTRA_SEARCH_QUERY";

    public static final String EXTRA_SEARCH_POSITON = PlayLv2.PACKAGE_NAME
    + ".SearchResultActivity.EXTRA_SEARCH_POSITON";
      
    private StateHolder mStateHolder;
    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
        
        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_SEARCH_TRIP)) {
            boolean isTrip = getIntent().getExtras().getBoolean(EXTRA_SEARCH_TRIP);
            mStateHolder.setIsTripType(isTrip);
        }
        
        if (getIntent().hasExtra(EXTRA_SEARCH_QUERY)) {
            String query = getIntent().getExtras().getString(EXTRA_SEARCH_QUERY);
            mStateHolder.setQuery(query);
        }
        if (getIntent().hasExtra(EXTRA_SEARCH_POSITON)) {
            int position = getIntent().getExtras().getInt(EXTRA_SEARCH_POSITON);
            mStateHolder.setPosition(position);
        }
        if(mStateHolder.getIsTripType() == true){
            mStateHolder.startTaskSearchTrip(this, (PlayLv2) getApplication());
        }else{
            mStateHolder.startTaskSearchTask(this, (PlayLv2) getApplication());
        }
        ensureUi();
    }
   
    private void ensureUi(){
        //mEmptyView = (View)findViewById(R.id.empty);
        
        getListView().setOnItemClickListener(new ListView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(mStateHolder.getSearchResult().getIsTrip() == true){
                    TripMini tripMini = mStateHolder.getSearchResult().getTrips().get(position);
                    Trip trip = new Trip();
                    trip.setId(tripMini.getId());
                    Intent intent = new Intent(SearchResultActivity.this, TripDetailsActivity.class);
                    trip.setUserId(((PlayLv2) getApplication()).getUserId());
                    intent.putExtra(TripDetailsActivity.EXTRA_TRIP_PARCEL, trip);
                    startActivity(intent);
                }else{
                    TaskMini taskMini = mStateHolder.getSearchResult().getTasks().get(position);
                    Task task = new Task();
                    Intent intent = new Intent(SearchResultActivity.this, AddTipsActivity.class);
                    intent.putExtra(AddTipsActivity.EXTRA_TASK_PARCEL, task);
                    startActivity(intent);
                }
            }

        });
    }
    private void onGetSearchResultTaskComplete(Group<TaskMini> results, Exception ex) {
        if ( results != null && results.size() > 0 ) {
            
            setProgressBarIndeterminateVisibility(false);
            SearchResult result = new SearchResult();
            result.setTasks(results);
            result.setIsTrip(false);
            mStateHolder.setSearchResult(result);
            SearchResultListAdapter adapter = new SearchResultListAdapter(this,
                    mStateHolder.getSearchResult(),((PlayLv2) getApplication()).getRemoteResourceManager());
            getListView().setAdapter(adapter);

        }else{
            setEmptyView();
        }
    }
    private void onGetSearchResultTripComplete(Group<TripMini> results, Exception ex) {
        
        if ( results != null && results.size() > 0 ) {
            setProgressBarIndeterminateVisibility(false);
            SearchResult result = new SearchResult();
            result.setTrips(results);
            result.setIsTrip(true);
            mStateHolder.setSearchResult(result);
            SearchResultListAdapter adapter = new SearchResultListAdapter(this,
                    mStateHolder.getSearchResult(),((PlayLv2) getApplication()).getRemoteResourceManager());
            getListView().setAdapter(adapter);

        }else{
            setEmptyView();
        }
    }
    private static class GetSearchResultTrip extends AsyncTask<Void, Void, Group<TripMini>> {

        private SearchResultActivity mActivity;
        private Exception mReason;
        private PlayLv2 mPlaylv2;
        private String mQuery;
        private int mSearchCategory;

        public GetSearchResultTrip(SearchResultActivity activity, PlayLv2 playlv2, String query, int searchCategory) {
            mActivity = activity;
            mPlaylv2 = playlv2;
            mQuery = query;
            mSearchCategory = searchCategory;
        }

        @Override
        protected  Group<TripMini> doInBackground(Void... params) {
            try {
                return mPlaylv2.getPlayLv2Api().searchTrip(mQuery, String.valueOf(mSearchCategory));

            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute( Group<TripMini> results) {
            if (mActivity != null) {
                mActivity.onGetSearchResultTripComplete(results, mReason);                
            }
        }

        protected void onCancelled() {
            if (mActivity != null) {
                mActivity.onGetSearchResultTripComplete(null, new Exception(
                        "Search action cancelled."));
            }
        }
    }
    private static class GetSearchResultTask extends AsyncTask<Void, Void, Group<TaskMini>> {

        private SearchResultActivity mActivity;
        private Exception mReason;
        private PlayLv2 mPlaylv2;
        private String mQuery;
        private int mSearchCategory;

        public GetSearchResultTask(SearchResultActivity activity, PlayLv2 playlv2, String query, int searchCategory) {
            mActivity = activity;
            mPlaylv2 = playlv2;
            mQuery = query;
            mSearchCategory = searchCategory;
        }

        @Override
        protected  Group<TaskMini> doInBackground(Void... params) {
            try {
                return mPlaylv2.getPlayLv2Api().searchTask(mQuery, String.valueOf(mSearchCategory));

            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute( Group<TaskMini> results) {
            if (mActivity != null) {
                mActivity.onGetSearchResultTaskComplete(results, mReason);                
            }
        }

        protected void onCancelled() {
            if (mActivity != null) {
                mActivity.onGetSearchResultTaskComplete(null, new Exception(
                        "Search action cancelled."));
            }
        }
    }

    private static class StateHolder {
        private GetSearchResultTrip mGetSearchResultTrip;
        private GetSearchResultTask mGetSearchResultTask;
        private SearchResult mResult;
        private boolean mIsTripType;
        private String mQuery;
        private int mPosition;

        public StateHolder() {
            mGetSearchResultTask = null;
            mIsTripType = true;
        }

        public void setIsTripType(boolean isTrip) {
            mIsTripType = isTrip;
        }
        
        public boolean getIsTripType(){
            return mIsTripType;
        }
        
        public void setSearchResult(SearchResult result){
            mResult = result;
        }
        
        public SearchResult getSearchResult(){
            return mResult;
        }
        
        public void setPosition(int position) {
            mPosition = position;
        }
        public void setQuery(String query){
            mQuery = query;
        }

        public void startTaskSearchTrip(SearchResultActivity activity, PlayLv2 playlv2) {
            mGetSearchResultTrip = new GetSearchResultTrip( activity, playlv2, mQuery, mPosition);
            mGetSearchResultTrip.execute();
        }
        public void startTaskSearchTask(SearchResultActivity activity, PlayLv2 playlv2) {
            mGetSearchResultTask = new GetSearchResultTask( activity, playlv2, mQuery, mPosition);
            mGetSearchResultTask.execute();
        }
    }
}
